using UnityEngine;
using UnityEditor;
using System.Collections;

[CustomEditor(typeof(PathBehaviour))]
public class PathInspector : Editor
{
	void OnEnable ()
	{
		m_sampleCountProperty = serializedObject.FindProperty ("m_sampleTimes");
	}
	
	public override void OnInspectorGUI ()
	{
		serializedObject.Update ();
		
		EditorGUILayout.BeginHorizontal ();
		EditorGUILayout.PropertyField (m_sampleCountProperty, GUILayout.MaxWidth (200));
		EditorGUILayout.Space ();
		if (GUILayout.Button ("Resample", GUILayout.MaxWidth (100)))
		{
			(target as PathBehaviour).sampleTimes = m_sampleCountProperty.intValue;
		}
		EditorGUILayout.EndHorizontal ();
		
		serializedObject.ApplyModifiedProperties ();
	}
	
	void OnSceneGUI ()
	{
		PathBehaviour bezierController = serializedObject.targetObject as PathBehaviour;
		
		Event evt = Event.current;
		if (evt.alt && evt.type == EventType.MouseDown && evt.button == 0 && evt.clickCount == 1)
		{
			if (!bezierController.curveCreated)
			{
				if (!bezierController.startAnchorSet)
				{
					bezierController.startAnchor = ScreenToTerrain (evt.mousePosition);
					EditorUtility.SetDirty (target);
				}
				else if (!bezierController.endAnchorSet)
				{
					bezierController.endAnchor = ScreenToTerrain (evt.mousePosition);
					EditorUtility.SetDirty (target);
				}
			}
		}
	}
	
	Vector3 ScreenToTerrain (Vector2 mousePosition)
	{
		Ray ray = HandleUtility.GUIPointToWorldRay (mousePosition);
		
		RaycastHit hit;
		if (Physics.Raycast (ray, out hit, Mathf.Infinity))
		{
			if ((hit.collider as TerrainCollider) != null)
			{
				Vector3 collisionPos = hit.point;
				collisionPos.y += 1.0f;
				return collisionPos;
			}
		}
		return Vector3.zero;
	}
	
	SerializedProperty m_sampleCountProperty;
	int m_sampleTimes;
}

